package com.oraycn.esbasic.tools;

import com.oraycn.esbasic.events.ManualResetEvent;

abstract class BaseCycleEngine implements Runnable {
    private ManualResetEvent manualResetEvent4Stop = new ManualResetEvent(false);
    private volatile boolean isStop = true;
    private  Thread thread ;

    @Override
    public void run() {
        try {
            cycleThread();
        }catch (Exception e){
            e.printStackTrace();
        }

        this.manualResetEvent4Stop.set();
    }

    protected  abstract  void cycleThread();

    public void start()
    {
        if (!this.isStop)
        {
            return;
        }

        this.manualResetEvent4Stop.reset();
        this.isStop = false;
        this.thread = new Thread(this);
        this.thread.start();
    }

    public  boolean isRunning()
    {
        return  !this.isStop ;
    }

    public void stop()
    {
        try {
            if (this.isStop) {
                return;
            }

            this.isStop = true;
            this.manualResetEvent4Stop.waitOne();
            this.manualResetEvent4Stop.reset();
        }catch (Exception e){}
    }
}
 